<?php
/**
 * 验证短信验证码并登录
 */

session_start();
header('Content-Type: application/json');

// 获取POST数据
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!isset($data['phone']) || !isset($data['code'])) {
    echo json_encode(['success' => false, 'message' => '请输入手机号和验证码']);
    exit;
}

$phone = $data['phone'];
$code = $data['code'];

// 检查session中是否有验证码
if (!isset($_SESSION['sms_code']) || !isset($_SESSION['sms_phone']) || !isset($_SESSION['sms_time'])) {
    echo json_encode(['success' => false, 'message' => '请先获取验证码']);
    exit;
}

// 验证手机号是否匹配
if ($_SESSION['sms_phone'] !== $phone) {
    echo json_encode(['success' => false, 'message' => '手机号不匹配']);
    exit;
}

// 验证码是否过期（5分钟）
if (time() - $_SESSION['sms_time'] > 300) {
    unset($_SESSION['sms_code'], $_SESSION['sms_phone'], $_SESSION['sms_time']);
    echo json_encode(['success' => false, 'message' => '验证码已过期，请重新获取']);
    exit;
}

// 验证码是否正确
if ($_SESSION['sms_code'] !== $code) {
    echo json_encode(['success' => false, 'message' => '验证码错误']);
    exit;
}

// 验证成功，清除验证码
unset($_SESSION['sms_code'], $_SESSION['sms_phone'], $_SESSION['sms_time']);

// 检查是否与管理员配置中的手机号匹配
$config = include __DIR__ . '/../../config.php';
$adminPhone = $config['admin_user']['phone'] ?? '';

if (empty($adminPhone)) {
    echo json_encode(['success' => false, 'message' => '管理员未配置手机号，无法使用短信登录']);
    exit;
}

if ($adminPhone !== $phone) {
    echo json_encode(['success' => false, 'message' => '该手机号未授权登录，请联系管理员']);
    exit;
}

// 设置登录session
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $config['admin_user']['username']; // 使用管理员配置的用户名
$_SESSION['phone'] = $phone;
$_SESSION['login_type'] = 'sms';

echo json_encode([
    'success' => true, 
    'message' => '登录成功',
    'redirect' => 'index.php'
]);
